package com.proxy.scanandcheck.checker.thread;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.http.client.HttpClient;

import com.proxy.scanandcheck.common.util.Constants;
import com.proxy.scanandcheck.common.valueobject.Proxy;

/**
 * Threadpool for management thread.
 *
 */
public class ThreadPool {

	/**
	 * Create thread pool, create a couple threads, pass proxy object and submit task to pool.
	 * When all the thread finish the return.
	 * @param myProxyList
	 */
	public void start(HttpClient httpclient,List<Proxy> myProxyList, List<String> words) {

		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(Constants.CORE_POOL_SIZE, Constants.MAX_POOL_SIZE, Constants.KEEP_ALIVE_TIME,
				TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(Constants.QUEUESIZE),
				new ThreadPoolExecutor.CallerRunsPolicy());

		for (String word : words) {
			for(Proxy myProxy : myProxyList)
			{
				try {
					threadPool.submit(new ThreadPoolTask(httpclient,myProxy,word));
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		// Wait for threads to finish off.
		threadPool.shutdown();
		try {
			// Wait for everything to finish.
			while (!threadPool.awaitTermination(2, TimeUnit.SECONDS)) {
//				System.out.println("Awaiting completion of threads.");
				Thread.sleep(100);
			}
			System.out.println("finished checking proxy");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
